/** request
 * 1. 请求失败自动重试，
 * 2. 错误收集、上报 (暂未处理)
 */

/**
 * url: 请求地址
 * data: 请求参数
 * method: 请求类型
 * type: 请求方式
 * timeout：超时限制
 * retry: 重试次数
 * delay：重试间隔时间
 */
import { API_ROOT } from '@/config/config.js'
import { useStore } from '@/store/index.js';
let store = '';
const request = async ({
  url,
  data,
  method = 'POST',
  type = 'request',
  timeout = 30000,
  retry = 3,
  delay = 2000,
  header = {}
}) => {
	if(!store){
		store = useStore(); // 赋值一次
	};
	let { v_userInfo } = store;
	(v_userInfo && v_userInfo.token) && (header.Authorization = v_userInfo.token); // 设置token
  const axiosOptions = {
    url: url.indexOf('http') < 0 ? API_ROOT + url : url,
    method,
    header,
    enableHttp2: true,
    timeout,
  };
  if (type === 'request') {
    axiosOptions.data = data;
  } else if (type === 'uploadFile' && data && JSON.stringify(data) !== '{}') {
    axiosOptions.filePath = data.filePath;
    delete data.filePath;
    axiosOptions.formData = data;
    axiosOptions.name = 'img_file';
  }
  let lastError = null;
  for (let i = 0; i < retry; i++) {
    try {
      const response = await uni[type](axiosOptions);
      const { statusCode, data: resData } = response;
      if (statusCode === 200) {
        const { code } = resData;
        return resData;
      } 
			else {
				lastError = resData;
        throw new Error(`请求失败，状态码为 ${statusCode}`);
      }
    } catch (error) {
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  uni.showToast({
    title: lastError.Message,
    icon: 'none'
  });
  // throw new Error lastError;
};

export { request };